<template>
  <div class="imou-player">
    <div
      id="imou-player"
      style="width: 100%; height: 100%; background-color: rgba(0, 48, 134, 0.60)!important;"
    ></div>
  </div>
</template>
<script>
var player = null;
export default {
  name: "ImouPlayer",
  mounted() {
    this.init();
  },
  watch: {
    $route: {
      handler(newRoute) {
        this.init();
      },
      immediate: false,
      deep: true
    }
  },
  methods: {
    destroy() {
      player.destroy();
      player = null;
    },
    parseToJson(str) {
      // 替换键和字符串值为双引号包裹
      let newStr = str.replace(/(\w+):/g, '"$1":');
      newStr = newStr.replace(/:([^",{}\[\]]+)/g, (match, p1) => {
        if (!isNaN(p1)) {
          return `:${p1}`; // 保持数字不变
        }
        return `:"${p1}"`;
      });
      return JSON.parse(newStr);
    },
    init() {
      const param = this.parseToJson(this.$route.params.param);
      try {
      if (!param.deviceId || !param.channelId || !param.token) {
        console.error('路由参数不完整，请检查 deviceId、channelId 和 token。');
        return;
      }
    } catch (error) {
      console.error('解析路由参数时出错:', error);
      return;
    }
      if (player) {
        this.destroy();
      }
      player = new imouPlayer({
        id: "imou-player",
        width: '100%',
        height: 500,
        deviceId: param.deviceId,
        channelId: param.channelId,
        token: param.token,
        // 1-Live 直播; 2-Playback 录播
        type: 1,
        // Live 0-HD 高清; 1-SD 标清
        streamId: 1,
        // 录播 云录像 cloud 本地录像 localRecord 默认 云录像
        // Playback, cloud-Cloud Video; localRecord-Local Video. Default Cloud Video
        recordType: "cloud",
        muted: false,
        handleError: (err) => {
          console.error("handleError", err);
        },
        
      });
      window.player = player;
      this.$nextTick(()=>{
        const div1=document.getElementById("imou-player");
        if (div1) {
          div1.style.backgroundColor = 'rgba(0, 48, 134, 0.60)';
        }
      })
    },
  },
};
</script>
<style scoped>
.imou-player {
  width: 100%;
  margin: 0 auto;
}
button {
  margin: 0 10px;
}
</style>